const setParams = (params) => {
  let queryArr = []
  for (let key in params) {
    let str = key + '=' + params[key]
    queryArr.push(str)
  }
  return queryArr.join('&')
}

function newAjax(option) {
  const p = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.responseType = 'json'
    const query = setParams(option.data)
    if (option.method.toUpperCase() === 'GET') {
      xhr.open('GET', query ? option.url + '?' + query : option.url)
      xhr.send()
    } else if (option.method.toUpperCase() === 'POST') {
      xhr.open('POST', option.url)
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      xhr.send(query)
    }

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(xhr.status)
        } else {
          reject(xhr.status)
        }
      }
    }
  })
  return p
}
